import { useState } from 'react'
import { Form, Input, Button, Typography } from 'antd'
import { UserOutlined } from '@ant-design/icons'
import PasswordInput from '@/components/PasswordInput'
import { onRegister } from '@/apis'

const { Item } = Form

function Register() {
    const [loading, setLoading] = useState(false)

    const toRegister = (data) => {
        if(loading) {
            return Promise.reject(false)
        }
        setLoading(true)
        onRegister(data).then((res) => {
            console.log('register success', res);
            window.location.href = '/login'
        })
        .catch(() => {})
        .finally(() => setLoading(false))
    }

    return <div className='flex h-screen items-center justify-center max-md:items-start'>
        <div className='p-16 w-[460px] bg-gray-50 rounded-md shadow-md max-md:w-screen max-md:rounded-none max-md:shadow-none max-md:bg-transparent max-md:p-4 max-md:text-lg' justify='space-around' align='middle'>

            <Typography.Title>注册</Typography.Title>
            <Form
                style={{ textAlign: 'left' }}
                layout="vertical"
                onFinish={toRegister}>
                <Item
                    label="用户名"
                    name="username"
                    rules={[{ required: true, message: '请输入你的用户名' }]}
                >
                    <Input size='large' maxLength={64} prefix={<UserOutlined />} />
                </Item>

                <Item
                    label="密码"
                    name="password"
                    rules={[{ required: true, message: '你输入你的登录密码' }]}
                >
                    <PasswordInput />
                </Item>

                <Item
                    label="确认密码"
                    name="confirm_password"
                    dependencies={['password']}
                    rules={[
                        { required: true, message: '二次确认登录密码' },
                        ({ getFieldValue }) => ({
                            validator(_, value) {
                              if (!value || getFieldValue('password') === value) {
                                return Promise.resolve();
                              }
                              return Promise.reject(new Error('两次密码输入不一致!'));
                            },
                          }),
                    ]}
                >
                    <Input.Password />
                </Item>

                <Item>
                    <Button size='large' type="primary" htmlType="submit" block loading={loading}>
                        立即注册
                    </Button>
                </Item>
            </Form>
        </div>
    </div>;
}

export default Register